package controller

import (
	"fmt"
	"gitee.com/kisgod/Lamborighi/Server/app/common"
	"gitee.com/kisgod/Lamborighi/Server/app/model"
	"github.com/gin-gonic/gin"
	"strconv"
)

type EnvController struct {
	Controller
}

func (ec *EnvController) GetEnv(c *gin.Context) {
	projectId, err := strconv.Atoi(c.Param("projectId"))
	if err != nil || projectId <= 0 {
		ec.ParamError(c)
		return
	}

	projectEnvs := model.GetEnvByProjectId(projectId)
	ec.response(c, Response{
		Status: ResSuccess,
		Data:   projectEnvs,
	})
}

func (ec *EnvController) UpdateEnv(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil || id <= 0 {
		ec.ParamError(c)
		return
	}

	var env model.Env
	if err := c.ShouldBindJSON(&env); err != nil {
		ec.ParamError(c)
		return
	}
	err = model.UpdateEnv(id, env)
	if err != nil {
		ec.response(c, Response{
			Status:    ResServerError,
			ErrorCode: common.Error,
			Error:     err.Error(),
		})
		return
	} else {
		ec.response(c, Response{
			Status: ResSuccess,
		})
		return

	}
}

func (ec *EnvController) AddEnv(c *gin.Context) {
	var env model.Env
	if err := c.ShouldBindJSON(&env); err != nil {
		fmt.Println(err)
		ec.ParamError(c)
		return
	}

	err := model.AddEnv(&env)
	if err != nil {
		ec.response(c, Response{
			Status:    ResServerError,
			ErrorCode: common.Error,
			Error:     "添加失败",
		})
		return
	} else {
		ec.response(c, Response{
			Status: ResSaved,
			Data:   env,
		})
		return
	}
}
